package com.demo.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.dao.UserMapper;
import com.demo.entity.User;

public class UserRealm extends AuthorizingRealm {

	@Autowired
	private UserMapper userMapper;

	public void setName(String name) {
		super.setName("userRealm");
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("执行了授权逻辑");
		User user = (User) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("执行了认证逻辑");
		System.out.println("this.getName():" + this.getName());
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		String name = upToken.getUsername();
		String password = new String(upToken.getPassword());

		//从数据库中查询用户信息
		QueryWrapper<User> qw = new QueryWrapper<User>();
		qw.eq("name", name);
		User user = userMapper.selectOne(qw);
		System.out.println(user);

		if (user == null) {
			// 用户名不存在
			return null; // shiro底层会抛出UnKnowAccountException
		}

		//内部做了密码比对.如果密码不正确,会抛出IncorrectCredentialsException
		return new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());

	}

}
